/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.purchase.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import com.jeeplus.modules.api.utils.MessageUtils;
import com.jeeplus.modules.source.entity.Source;
import com.jeeplus.modules.source.service.SourceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.purchase.entity.Purchase;
import com.jeeplus.modules.purchase.mapper.PurchaseMapper;

import javax.annotation.Resource;

/**
 * 求购Service
 * @author zhych
 * @version 2021-12-09
 */
@Service
@Transactional(readOnly = true)
public class PurchaseService extends CrudService<PurchaseMapper, Purchase> {

	@Resource
	private MessageUtils messageUtils;

	@Resource
	private SourceService sourceService;

	public Purchase get(String id) {
		return super.get(id);
	}
	
	public List<Purchase> findList(Purchase purchase) {
		return super.findList(purchase);
	}
	
	public Page<Purchase> findPage(Page<Purchase> page, Purchase purchase) {
		return super.findPage(page, purchase);
	}
	
	@Transactional(rollbackFor = Exception.class)
	public void save(Purchase purchase) {
		super.save(purchase);
	}

	@Transactional(rollbackFor = Exception.class)
	public void saveAndSendMsg(Purchase purchase,String sourceNotify,String sourceUri) {
		super.save(purchase);
		// 查询车源列表
		Source source = new Source();
		source.setBrand(purchase.getBrand())
				.setMotorclcleType(purchase.getMotorcycleType())
				.setCarStyle(purchase.getCarStyle())
				.setColour(purchase.getColour())
				.setShiftType(purchase.getShiftType())
				.setRegistrationDate(purchase.getRegisteredDate())
				.setMileage(purchase.getMileage())
				.setIsUp("1");
		source.setBrand(purchase.getBrand());
		BigDecimal bigDecimal = new BigDecimal(purchase.getCarBudget()).setScale(1, RoundingMode.HALF_UP);
		source.setDataScope("  AND (a.ls_price BETWEEN '" + bigDecimal + "' AND '" + (bigDecimal.add(new BigDecimal("1.00"))).setScale(1, RoundingMode.HALF_UP) + "')");
		List<Source> list = sourceService.findList(source);
		if (CollUtil.isNotEmpty(list)) {
			// 查找车源id
			list.forEach(p -> {
				// 查找用户
				List<String> openIds = list.stream().map(o -> o.getU().getOpenid()).collect(Collectors.toList());
				openIds.forEach(o -> messageUtils.newPurchaseNotify(o, sourceNotify, sourceUri, p));
			});
		}
	}

	@Transactional(readOnly = false)
	public void delete(Purchase purchase) {
		super.delete(purchase);
	}
	
}